package org.tamal.jsf;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.tamal.Constants;

/**
 * This will validate whether the password is strong or not.
 * @author Tamal Kanti Nath
 */
@FacesValidator("StrongPasswordValidator")
public final class StrongPasswordValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component,
            Object value) {
        String str = (String) value;
        if (str == null || str.isEmpty()) {
            return;
        }
        if        (str.matches(".*\\p{Lower}.*")
                && str.matches(".*\\p{Upper}.*")
                && str.matches(".*\\p{Digit}.*")
                && str.matches(".*\\p{Punct}.*")) {
            return;
        }
        ResourceBundle rb = context.getApplication()
                .getResourceBundle(context, Constants.MSG);
        FacesMessage msg = new FacesMessage();
        String message = component.getClientId() + ": "
                + rb.getString("login.password.strong");
        msg.setSummary(message);
        msg.setSeverity(FacesMessage.SEVERITY_WARN);
        throw new ValidatorException(msg);
    }

}
